<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户信息</p>
    </div>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户名、姓名或手机号"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-select
            v-model="searchForm.role"
            placeholder="用户角色"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="患者" :value="1" />
            <el-option label="医生" :value="2" />
            <el-option label="管理员" :value="3" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-select
            v-model="searchForm.status"
            placeholder="用户状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="锁定" :value="2" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表（共 {{ pagination.total }} 条）</span>
          <div class="header-actions">
            <el-button size="small" @click="exportUsers">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button size="small" @click="refreshList">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'danger' : 'info'" size="small">
              {{ getGenderText(row.gender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="showEditDialog(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="warning" link size="small" @click="resetPassword(row)">
              <el-icon><Key /></el-icon>
              重置密码
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button type="info" link size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="`status-${row.id}`">
                    {{ row.status === 1 ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item :command="`delete-${row.id}`" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { addDialog } from '@/components/gDialog/index'
import UserHandle from './adminModal/userHandle.vue'
import { 
  getUserList, 
  deleteUser, 
  updateUserStatus, 
  resetUserPassword 
} from '@/api/admin'

// 响应式数据
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 用户列表
const userList = ref([])

// 选中的用户
const selectedUsers = ref([])

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      keyword: searchForm.keyword,
      role: searchForm.role,
      status: searchForm.status
    }
    
    const response = await getUserList(params)
    if (response.code === 200) {
      userList.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  pagination.page = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.role = ''
  searchForm.status = ''
  handleSearch()
}

// 刷新列表
const refreshList = () => {
  fetchUserList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchUserList()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 显示添加对话框
const showAddDialog = () => {
  addDialog({
    title: '添加用户',
    component: UserHandle,
    width: '600px',
    props: {
      isEdit: false,
      userData: {}
    },
    callBack: (result, data) => {
      if (result === 'success') {
        fetchUserList()
      }
    }
  })
}

// 显示编辑对话框
const showEditDialog = (row) => {
  addDialog({
    title: '编辑用户',
    component: UserHandle,
    width: '600px',
    props: {
      isEdit: true,
      userData: row
    },
    callBack: (result, data) => {
      if (result === 'success') {
        fetchUserList()
      }
    }
  })
}

// 重置密码
const resetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户 ${row.name} 的密码吗？密码将重置为 123456`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await resetUserPassword(row.id, {
      newPassword: '123456',
      sendNotification: true
    })
    
    if (response.code === 200) {
      ElMessage.success('密码重置成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

// 更多操作
const handleMoreAction = async (command, row) => {
  const [action, id] = command.split('-')
  
  if (action === 'status') {
    try {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      await ElMessageBox.confirm(
        `确定要${statusText}用户 ${row.name} 吗？`,
        `${statusText}用户`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      const response = await updateUserStatus(id, {
        status: newStatus,
        reason: `管理员${statusText}操作`
      })
      
      if (response.code === 200) {
        ElMessage.success(`${statusText}成功`)
        fetchUserList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('操作失败')
      }
    }
  } else if (action === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户 ${row.name} 吗？此操作不可恢复！`,
        '删除用户',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
      )
      
      const response = await deleteUser(id)
      
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchUserList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
}

// 导出用户
const exportUsers = () => {
  ElMessage.info('导出功能开发中...')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取性别文本
const getGenderText = (gender) => {
  const genderMap = { 0: '未知', 1: '男', 2: '女' }
  return genderMap[gender] || '未知'
}

// 获取角色文本
const getRoleText = (role) => {
  const roleMap = { 1: '患者', 2: '医生', 3: '管理员' }
  return roleMap[role] || '未知'
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = { 1: 'info', 2: 'success', 3: 'warning' }
  return typeMap[role] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = { 0: '禁用', 1: '正常', 2: '锁定', 3: '待激活' }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = { 0: 'danger', 1: 'success', 2: 'warning', 3: 'info' }
  return typeMap[status] || 'info'
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-card .el-row .el-col {
    margin-bottom: 12px;
  }
  
  .table-card :deep(.el-table) {
    font-size: 12px;
  }
  
  .table-card :deep(.el-table .el-button) {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style> 